<?php

namespace app\common\model;

use app\common\model\order\OrderItem;
use think\Model;
use traits\model\SoftDelete;

class Order extends Model
{
    // 表名
    use SoftDelete;



    // 表名
    protected $name = 'order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [
        'status_text',
        'pay_status_text',
        'order_status_text',
        'cancel_time_text',
        'refund_status_text',
        'is_appoint_text',
        'pay_type_text',
        'paytime_text',
        'platform_text',
        'order_date_text',
    ];

    public function getOrderDateTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['rights_endtime']) ? $data['rights_endtime'] : '');
        return is_numeric($value) ? date("Y-m-d", $value) : $value;
    }
    public $checkinfoList = ['待付款','待预约','已完成','全部退款','已取消'];

    public function getStatusList()
    {
        return ['-2' => __('Status -2'), '-1' => __('Status -1'), '0' => __('Status 0'), '1' => __('Status 1'), '2' => __('Status 2'), '3' => __('Status 3')];
    }

    public function getPayStatusList()
    {
        return ['10' => __('Pay_status 10'), '20' => __('Pay_status 20')];
    }

    public function getOrderStatusList()
    {
        return ['-2' => __('Order_status -2'), '-1' => __('Order_status -1'), '0' => __('Order_status 0'), '1' => __('Order_status 1'), '2' => __('Order_status 2'), '3' => __('Order_status 3')];
    }

    public function getRefundStatusList()
    {
        return ['0' => __('Refund_status 0'), '1' => __('Refund_status 1'), '2' => __('Refund_status 2')];
    }

    public function getIsAppointList()
    {
        return ['0' => __('Is_appoint 0'), '1' => __('Is_appoint 1')];
    }

    public function getPayTypeList()
    {
        return ['wechat' => __('Pay_type wechat'), 'alipay' => __('Pay_type alipay'), 'wallet' => __('Pay_type wallet'), 'score' => __('Pay_type score')];
    }

    public function getPlatformList()
    {
        return ['H5' => __('Platform h5'), 'wxOfficialAccount' => __('Platform wxofficialaccount'), 'wxMiniProgram' => __('Platform wxminiprogram'), 'App' => __('Platform app')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getPayStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_status']) ? $data['pay_status'] : '');
        $list = $this->getPayStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function orderitem()
    {
        return $this->hasMany(OrderItem::class,'order_id','id');
    }
    public function getOrderStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['order_status']) ? $data['order_status'] : '');
        $list = $this->getOrderStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getCancelTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['cancel_time']) ? $data['cancel_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getRefundStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['refund_status']) ? $data['refund_status'] : '');
        $list = $this->getRefundStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getIsAppointTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['is_appoint']) ? $data['is_appoint'] : '');
        $list = $this->getIsAppointList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getPayTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_type']) ? $data['pay_type'] : '');
        $list = $this->getPayTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getPaytimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['paytime']) ? $data['paytime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getPlatformTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['platform']) ? $data['platform'] : '');
        $list = $this->getPlatformList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected function setCancelTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setPaytimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }
    public function order_sure($param,$is_submit=1)
    {

        if (isset($param['data'])) {

            $goodsList = [];
            foreach ($param['data'] as $k => $v) {
                $goodsList[$v['goodsId']] = $v['num'];
            }
            $goods_key = array_keys($goodsList);
            # 执行SQL查询, 获取商品信息.
            $query = model('goods')
                ->alias('a');
         //   $query->join(config('prefix') . 'spec_goods_price b', 'b.goods_id=a.id', 'LEFT');
         $query->field("a.*,concat_ws('-',a.id) as goods_id_key");

          $query->having("goods_id_key in ('" . implode("','", $goods_key) . "')");
            $rows = $query->select();



            # 加入购买数量
            # 统计信息
            $pay_price = $total_price = $total =$goods_amount=$total_fee= 0;
            $order_date='';
            $appoints=0;
            foreach ($rows as $key => $row) {

                $order_date=$row['enddate'];
                $row['buy_num'] = $goodsList[$row['goods_id_key']];
                #单品总价,根据有无规格选择不同商品价格
                $row['goods_image'] = cdnurl($row['goods_image'],true);
                $row['goodsmoney'] = $row['sales_price'];
                //$row['sku_text']=$row['sku_text'];
                $row['amount'] = $row['goodsmoney'] * $row['buy_num'];
                $row['total_price'] = $row['goodsmoney'] * $row['buy_num'];
                $goods_amount +=$row['amount'];
                $appoints+=$row['rights_num']*$row['buy_num'];
                $row['fee'] = 0;


                // 总金额
                $total_price =$total_price+ $row['fee']+$row['total_price'];

                // 总数量
                $total += $row['buy_num'];
                // 更新rows
                $rows[$key] = $row;
            }







            $pay_price =round($total_price , 2);
            $total_fee=$pay_price;
            return [
                'code' => 1,
                'msg' => '查询成功',
                'data' => $rows,
                'total' => $total,
                'appoints'=>$appoints,
                'order_date1'=>$order_date,
                'order_date'=>date('Y.m.d',$order_date),
                'total_fee'=>sprintf("%.2f", $total_fee),
                'goods_amount'=>sprintf("%.2f", $goods_amount),
                'total_price' => sprintf("%.2f", $total_price),
                'pay_price' =>sprintf("%.2f", $pay_price)
            ];
        } else {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
    }

    //生成订单
    public function create_order($param = '')
    {
        if (is_array($param) && isset($param['uid'])) {

            $orderSure = $this->order_sure($param);
            if ($orderSure['code'] == 400) {
                return $orderSure;
            } else {




                //获取毫秒
                list($usec, $sec) = explode(" ", microtime());
                $msec = round($usec * 1000);
                $pay_no = getOrderNo($param['uid']);


                //生成订单
                $data['order_sn'] = getOrderNo($param['uid']);
                $data['user_id'] = $param['uid'];
                $data['goods_amount']=$orderSure['goods_amount'];
                $data['total_amount']=$orderSure['total_price'];
                $data['total_fee'] = $orderSure['total_price'];
                $data['pay_fee'] = $orderSure['pay_price'];
                $data['pay_status'] = '10';
                $data['remark']=$param['note'];
                $data['status'] = 0;
                $data['order_status']=0;
                $data['used_appoints']=0;
                $data['appoints']=$orderSure['appoints'];
                $data['refund_status'] = 0;
                $data['createtime'] = time();
                $data['order_date']=$orderSure['order_date1'];
                $data['goods_num'] = $orderSure['total'];
                $cancel_time = config('site.cancel_time')?config('site.cancel_time'):0.5;
                if(is_numeric($cancel_time)){
                    if($cancel_time<=0){
                        $cancel_time=0.5;
                    }
                }else{
                    $cancel_time=0.5;
                }
                $data['pre_time']=$data['createtime']+$cancel_time*3600;

            }




            db()->startTrans();
            //订单收货信息
            $order = $this->save($data);
            $data2['order_id'] = $this->id;

            $discount = 1;


            foreach ($orderSure['data'] as $k => $v) {
                $data3['user_id']=$param['uid'];
                $data3['goods_id'] = $v['id'];
                $data3['goods_title'] = $v['goods_title'];
                $data3['goods_image'] = $v['goods_image'] ;
                $data3['goods_images'] = $v['goods_images'] ;

                $data3['goods_key'] = '';
                $data3['key_name'] =  '';

                $data3['goods_num'] = $v['buy_num'];
                $data3['total_price'] = $v['total_price'];
                $data3['total_fee']=$v['total_price'];
                $data3['pay_price']=$v['total_price'];
                $data3['total_amount']=$v['total_price'];
                $data3['total_num']=$v['buy_num'];
                $data3['content']=$v['goods_content'];
                $data3['rights_title']=$v['rights_title'];
                $data3['rights_card']=$v['rights_card'];
                $data3['rights_tags']=$v['rights_tags'];
                $data3['rights_num']=$v['rights_num'];
                $data3['total_rights_num']=$v['rights_num']*$v['buy_num'];
                $data3['used_num']=0;
                $data3['canuse_num']=0;
                $data3['goods_price']=$v['sales_price'];
                $data3['rights_content']=$v['rights_content'];
                $data3['hospital_ids']=$v['hospital_ids'];
                $tags=db('goods_tags')
                    ->where('id','in',$data3['rights_tags'])
                    ->group('tag_name')->column('tag_name');
                $data3['tags']=implode(',',$tags);
                $data3['tag_ids']=$v['tag_ids'];
                $tags_names=db('goods_tags')
                    ->where('id','in',$data3['rights_tags'])
                    ->group('tag_name')->column('tag_name');
                $data3['tag_names']=implode(',',$tags_names);
                $data3['rights_desc']=$v['rights_desc'];
                $data3['rights_memo']=$v['rights_memo'];
                $data3['refund_fee']=0;
                $data3['rights_endtime']=$v['enddate'];
                $data3['order_id'] = $this->id;

                $data3['createtime'] = time();
                $data3['is_all']=$v['is_all'];



                $res = db('order_item')->insertGetId($data3);
                $tags_ids= explode(',',$v['tag_ids']);
                $m_saves=[];
                $createtime=time();
                foreach ($tags_ids as $k3=>$v3){
                    $mid=\db('goods_tags')->where(['id'=>$v3])->value('tag_name');
                    if(!$mid){
                    }else{
                        $m_saves[]=['user_id'=>$param['uid'],
                            'order_item_id'=>$res,
                            'goods_id'=>$v['id'],
                            'order_id'=>$this->id,'tag_id'=>$v3,
                            'tag_name'=>$mid,'createtime'=>$createtime];
                    }
                }
                \db('order_item_examine')->insertAll($m_saves);

                   db('goods')->where('id', $v['id'])->setInc('goods_sales', $v['buy_num']);
                $res3 = db('goods')->where('id', $v['id'])->setDec('goods_num', $v['buy_num']);


                // }
                //所有商品规格的销量增加

                if ($res  && $res3 !== false) {

                    continue;
                } else {
                    db()->rollback();
                    return ['code' => 400, 'msg' => '生成订单失败'];
                    break;
                }
            }

            if ($order ) {
                db()->commit();
                return ['code' => 200, 'msg' => '订单创建成功', 'order_id' => $this->id];
            } else {
                db()->rollback();
                return ['code' => 400, 'msg' => '订单创建失败'];
            }
        } else {
            return ['code' => 400, 'msg' => '数据异常'];
        }
    }
}
